package gitobject;

import repository.Repository;
import sha1.SHA1;
import zlib.ZLibUtils;
import fileoperation.FileReader;
import  core.*;
import commander.init;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Blob extends GitObject{
    
	public String getFmt(){
        return fmt;
    }
    public String getMode(){ return mode; }
    public String getPath(){ return path; }
    public String getValue(){ return value; }
    public String getKey() { return key; }
    public Blob(){} //构造函数
    /**
     * Constructing blob object from a file
     */
    public Blob(File file) throws Exception {
        this.fmt  = "blob";
        this.mode = "100644";   //100表示普通文件，644表示可读可写
        this.value = getValue(file);
        this.file = file;
        genKey(file);
        //   compressWrite();
        writeObject();//反序列化时直接用readObject读取对象
    }

    /**
     * Deserialize a blob object from an existed hash file in .jit/objects.
     * @param Id  id代表类对象文件名如：100644 blob 5cc141890cf0e01b951c1c1358b5afca9cda3977 test.txt
     */

    public Blob(String Id) throws IOException {
        this.fmt = "blob";
        this.mode = "100644";
        try{
            File file = new File(path + File.separator + Id);
            if(file.exists()){
                ObjectInputStream oos = new ObjectInputStream(new FileInputStream(file));
                this.value = (String) oos.readObject();
                //反序列化生成blob的value值
                this.key = Id;
                this.file = new File(Repository.getWorkTree() + File.separator + Id);
                //恢复工作区上文件
            }
            else {
                System.out.println("Id not exists");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * Generate key from file.
     * @return String
     */
    //文件哈希加密,调用抽象类SHA1
    public String genKey(File file) throws Exception {
        try {
            key = SHA1.getHash(file);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return key;
    }

    @Override
    public String toString(){
        return "100644 blob " + key + " " + this.file.getName();
    }

   /* public static void main(String[] args){
        try{
            new JitInit().init("C:/Users/之靈/Desktop/Git");
            new init().init();
            File f1 = new File("C:/Users/之靈/Desktop/Git" + File.separator + "test.txt");
            String key = SHA1.getHash(f1);
            System.out.println(f1.exists());
            Blob blob = new Blob(f1);

        }
        catch (Exception e){
            e.printStackTrace();
        }
    }*/
}
